package com.syezon.wifikey.ad;

import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.hodanet.appadvplatclient.ReportAgent;
import com.hodanet.appadvplatclient.ad.AdInfo;
import com.qq.e.ads.banner2.UnifiedBannerADListener;
import com.qq.e.ads.banner2.UnifiedBannerView;
import com.qq.e.comm.util.AdError;
import com.syezon.wifikey.channel.ChannelConfig;
import com.syezon.wifikey.config.GDTConfig;
import com.syezon.wifikey.config.TTAdManagerHolder;
import com.syezon.wifikey.splash.config.SplashConfig;

import java.util.List;

public class BannerAd {
    private UnifiedBannerView mBannerView;
    private TTNativeExpressAd mTTNativateExpressAd;
    private ViewGroup viewGroup;
    private Activity activity;
    private CommonAdCallBack commonAdCallBack;
    private CommonNewAdCallBack commonNewAdCallBack;

    public void setCommonNewAdCallBack(CommonNewAdCallBack commonNewAdCallBack) {
        this.commonNewAdCallBack = commonNewAdCallBack;
    }

    public void setCommonAdCallBack(CommonAdCallBack commonAdCallBack) {
        this.commonAdCallBack = commonAdCallBack;
    }

    public BannerAd(Activity activity, ViewGroup viewGroup) {
        this.viewGroup = viewGroup;
        this.activity = activity;
    }


    public void loadBannerAdByAdInfo(AdInfo adInfo) {
        if (adInfo == null) {
            return;
        }

        if (adInfo.getType() == AdInfo.AD_TYPE_CHUAN_SHAN_JIA) {
            loadCsjBannerAd(adInfo);
        } else if (adInfo.getType() == AdInfo.AD_TYPE_GUANG_DIAN_TONG) {
            loadGdtBannerAd(adInfo);
        }
    }

    public void loadBannerAdByAdInfo(String code) {
        if (TextUtils.isEmpty(code)) {
            return;
        }

        if (SplashConfig.SPLASH_AD_SOURCE_GDT.equals(code)) {
            loadGdtBannerAd(code);
        } else if (SplashConfig.SPLASH_AD_SOURCE_TT.equals(code)) {
            loadCsjBannerAd(TTAdManagerHolder.ME_BOTTOM_BANNER);
        }
    }

    private void loadCsjBannerAd(final String code){
        try {
            //设置广告参数
            AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId(code) //广告位id
                    .setSupportDeepLink(true)
                    .setExpressViewAcceptedSize(360, 0) //期望模板广告view的size,单位dp
                    .setImageAcceptedSize(640, 320)//这个参数设置即可，不影响模板广告的size
                    .build();
            //加载广告
            TTAdManagerHolder.get().createAdNative(Utils.getApp()).loadBannerExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
                @Override
                public void onError(int i, String s) {
                    LogUtils.e("CSJ onError " + s);
                    viewGroup.removeAllViews();
                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, code, SDKReportHelper.OP_TYPE_FAIL);
                    if (commonAdCallBack != null) {
                        commonAdCallBack.onLoadFail(code, s);
                    }
                }

                @Override
                public void onNativeExpressAdLoad(List<TTNativeExpressAd> list) {
                    LogUtils.e("CSJ onNativeExpressAdLoad " + list);
                    if (list == null || list.isEmpty()) {
                        return;
                    }
                    TTNativeExpressAd ttNativeExpressAd = list.get(0);
                    if (ttNativeExpressAd == null) {
                        return;
                    }
                    mTTNativateExpressAd = ttNativeExpressAd;
                    mTTNativateExpressAd.render();
                    bindAdListener(mTTNativateExpressAd, code);
                }
            });

        } catch (Exception e) {

        }
    }

    private void loadCsjBannerAd(final AdInfo adInfo) {
        try {
            //设置广告参数
            AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId(adInfo.getCode()) //广告位id
                    .setSupportDeepLink(true)
                    .setExpressViewAcceptedSize(360, 0) //期望模板广告view的size,单位dp
                    .setImageAcceptedSize(640, 320)//这个参数设置即可，不影响模板广告的size
                    .build();
            //加载广告
            TTAdManagerHolder.get().createAdNative(Utils.getApp()).loadBannerExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
                @Override
                public void onError(int i, String s) {
                    LogUtils.e("CSJ onError " + s);
                    viewGroup.removeAllViews();
                    ReportAgent.reportAdvSdkFailed(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                    if (commonNewAdCallBack != null) {
                        commonNewAdCallBack.onLoadFail(adInfo, s);
                    }
                }

                @Override
                public void onNativeExpressAdLoad(List<TTNativeExpressAd> list) {
                    LogUtils.e("CSJ onNativeExpressAdLoad " + list);
                    if (list == null || list.isEmpty()) {
                        return;
                    }
                    TTNativeExpressAd ttNativeExpressAd = list.get(0);
                    if (ttNativeExpressAd == null) {
                        return;
                    }
                    mTTNativateExpressAd = ttNativeExpressAd;
                    mTTNativateExpressAd.render();
                    bindAdListener(mTTNativateExpressAd, adInfo);
                }
            });

        } catch (Exception e) {

        }
    }

    //绑定广告行为
    private void bindAdListener(TTNativeExpressAd ad, final String code) {
        ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {

            boolean reportShow;

            @Override
            public void onAdClicked(View view, int type) {
                LogUtils.e("CSJ onAdClicked ");
                SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, code, SDKReportHelper.OP_TYPE_CLICK);
            }

            @Override
            public void onAdShow(View view, int type) {
                if (commonAdCallBack != null) {
                    commonAdCallBack.onLoadSuccess(code);
                }
                LogUtils.e("CSJ onAdShow ");
                if (!reportShow) {
                    reportShow = true;
                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ,code, SDKReportHelper.OP_TYPE_SHOW);
                }
            }

            @Override
            public void onRenderFail(View view, String msg, int code) {
                LogUtils.e("CSJ onRenderFail ");
            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
                //在渲染成功回调时展示广告，提升体验
                LogUtils.e("CSJ onRenderSuccess ");
                viewGroup.removeAllViews();
                viewGroup.addView(view);
            }
        });
        ad.setDownloadListener(new TTAppDownloadListener() {

            boolean reportDownload;
            boolean reportInstall;

            @Override
            public void onIdle() {

            }

            @Override
            public void onDownloadActive(long l, long l1, String s, String s1) {

            }

            @Override
            public void onDownloadPaused(long l, long l1, String s, String s1) {

            }

            @Override
            public void onDownloadFailed(long l, long l1, String s, String s1) {

            }

            @Override
            public void onDownloadFinished(long l, String s, String s1) {
                if (!reportDownload) {
                    reportDownload = true;
                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, code, SDKReportHelper.OP_TYPE_DOWNLOAD);
                }
            }

            @Override
            public void onInstalled(String s, String s1) {
                if (!reportInstall) {
                    reportInstall = true;
                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, code, SDKReportHelper.OP_TYPE_INSTALL);
                }
            }
        });
    }


    //绑定广告行为
    private void bindAdListener(final TTNativeExpressAd ad, final AdInfo adInfo) {
        ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {

            boolean reportShow;

            @Override
            public void onAdClicked(View view, int type) {
                LogUtils.e("CSJ onAdClicked ");
                ReportAgent.reportAdvClick(adInfo,ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
            }

            @Override
            public void onAdShow(View view, int type) {
                if (commonNewAdCallBack != null) {
                    commonNewAdCallBack.onLoadSuccess(adInfo);
                }
                LogUtils.e("CSJ onAdShow ");
                if (!reportShow) {
                    reportShow = true;
                    ReportAgent.reportAdvExtShow(adInfo,ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                }
            }

            @Override
            public void onRenderFail(View view, String msg, int code) {
                LogUtils.e("CSJ onRenderFail ");
            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
                //在渲染成功回调时展示广告，提升体验
                LogUtils.e("CSJ onRenderSuccess ");
                viewGroup.removeAllViews();
                viewGroup.addView(view);
            }
        });
        ad.setDownloadListener(new TTAppDownloadListener() {

            boolean reportDownload;
            boolean reportInstall;

            @Override
            public void onIdle() {

            }

            @Override
            public void onDownloadActive(long l, long l1, String s, String s1) {

            }

            @Override
            public void onDownloadPaused(long l, long l1, String s, String s1) {

            }

            @Override
            public void onDownloadFailed(long l, long l1, String s, String s1) {

            }

            @Override
            public void onDownloadFinished(long l, String s, String s1) {
                if (!reportDownload) {
                    reportDownload = true;
                    ReportAgent.reportAdvDownload(adInfo,ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                }
            }

            @Override
            public void onInstalled(String s, String s1) {
                if (!reportInstall) {
                    reportInstall = true;
                    ReportAgent.reportAdvInstall(adInfo,ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                }
            }
        });
    }


    private void loadGdtBannerAd(final AdInfo adInfo) {
        try {
            if (mBannerView != null) {
                viewGroup.removeAllViews();
                mBannerView.destroy();
            }
            mBannerView = new UnifiedBannerView(activity, GDTConfig.APP_ID, adInfo.getCode(), new UnifiedBannerADListener() {

                boolean reportShow;

                @Override
                public void onNoAD(AdError adError) {
                    LogUtils.e("GDT onNoAD " + adError.getErrorMsg());
                    ReportAgent.reportAdvSdkFailed(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                }

                @Override
                public void onADReceive() {
                    LogUtils.e("GDT onADReceive");
                }

                @Override
                public void onADExposure() {
                    LogUtils.e("GDT onADExposure");
                    if (!reportShow) {
                        reportShow = true;
                        ReportAgent.reportAdvExtShow(adInfo,ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                    }
                }

                @Override
                public void onADClosed() {
                    LogUtils.e("GDT onADClosed");
                }

                @Override
                public void onADClicked() {
                    LogUtils.e("GDT onADClicked");
                    ReportAgent.reportAdvClick(adInfo,ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                }

                @Override
                public void onADLeftApplication() {
                    LogUtils.e("GDT onADLeftApplication");
                }

                @Override
                public void onADOpenOverlay() {
                    LogUtils.e("GDT onADOpenOverlay");
                }

                @Override
                public void onADCloseOverlay() {
                    LogUtils.e("GDT onADCloseOverlay");
                }
            });
            // 注意：如果开发者的banner不是始终展示在屏幕中的话，请关闭自动刷新，否则将导致曝光率过低。
            // 并且应该自行处理：当banner广告区域出现在屏幕后，再手动loadAD。
            if (commonNewAdCallBack != null) {
                commonNewAdCallBack.onLoadSuccess(adInfo);
            }
            mBannerView.setRefresh(30);
            viewGroup.removeAllViews();
            viewGroup.addView(mBannerView, getUnifiedBannerLayoutParams());
            mBannerView.loadAD();
        } catch (Exception e) {

        }
    }

    private void loadGdtBannerAd(final String code) {
        try {
            if (mBannerView != null) {
                viewGroup.removeAllViews();
                mBannerView.destroy();
            }
            mBannerView = new UnifiedBannerView(activity, GDTConfig.APP_ID, code, new UnifiedBannerADListener() {

                boolean reportShow;

                @Override
                public void onNoAD(AdError adError) {
                    LogUtils.e("GDT onNoAD " + adError.getErrorMsg());
                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_GDT, code, SDKReportHelper.OP_TYPE_FAIL);
                }

                @Override
                public void onADReceive() {
                    LogUtils.e("GDT onADReceive");
                }

                @Override
                public void onADExposure() {
                    LogUtils.e("GDT onADExposure");
                    if (!reportShow) {
                        reportShow = true;
                        SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_GDT,code, SDKReportHelper.OP_TYPE_SHOW);
                    }
                }

                @Override
                public void onADClosed() {
                    LogUtils.e("GDT onADClosed");
                }

                @Override
                public void onADClicked() {
                    LogUtils.e("GDT onADClicked");
                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_GDT, code, SDKReportHelper.OP_TYPE_CLICK);
                }

                @Override
                public void onADLeftApplication() {
                    LogUtils.e("GDT onADLeftApplication");
                }

                @Override
                public void onADOpenOverlay() {
                    LogUtils.e("GDT onADOpenOverlay");
                }

                @Override
                public void onADCloseOverlay() {
                    LogUtils.e("GDT onADCloseOverlay");
                }
            });
            // 注意：如果开发者的banner不是始终展示在屏幕中的话，请关闭自动刷新，否则将导致曝光率过低。
            // 并且应该自行处理：当banner广告区域出现在屏幕后，再手动loadAD。
            mBannerView.setRefresh(30);
            viewGroup.addView(mBannerView, getUnifiedBannerLayoutParams());
            mBannerView.loadAD();
        } catch (Exception e) {

        }
    }

    /**
     * banner2.0规定banner宽高比应该为6.4:1 , 开发者可自行设置符合规定宽高比的具体宽度和高度值
     *
     * @return
     */
    private FrameLayout.LayoutParams getUnifiedBannerLayoutParams() {
        return new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
    }

    public void destroy(){
        if(mBannerView != null){
            mBannerView.destroy();
        }

        if(mTTNativateExpressAd != null){
            mTTNativateExpressAd.destroy();
        }
    }
}
